{% load static %}
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>NewEra Systems</title>
    <!-- 预连接，加速CDN资源加载 -->
    <link rel="preconnect" href="https://cdn.jsdelivr.net" crossorigin>
    <link rel="preconnect" href="https://unpkg.com" crossorigin>
    <link rel="dns-prefetch" href="https://cdn.jsdelivr.net">
    <link rel="dns-prefetch" href="https://unpkg.com">
    <!-- 本地化CSS字体图标 -->
    <link rel="stylesheet" href="/static/font/bootstrap-icons.css">
    <!-- 使用最新版（推荐） 图标库  -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <!-- Bootstrap 5 本地加载方案 -->
    <link rel="stylesheet" href="{% static 'bootstrap5.23/bootstrap.min.css' %}">
    <!-- 通过版本号防止缓存: favicon.ico-->
    <link rel="icon" href="{% static 'favicon.ico' %}?v=2023">
    <!-- Swal提示框CSS文件 -->
    <link rel="stylesheet" href="https://unpkg.com/sweetalert2@11/dist/sweetalert2.min.css">
    <!-- 图片裁剪框样式-->
    <link href="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.5.12/cropper.min.css" rel="stylesheet">


    {% block title %} {% endblock %}
    {% block link %} {% endblock %}

    <style>
        :root {
            --bg-color: #000;
            --nav-bg: #1a1a1a;
            --border-color: #333;
            --text-primary: #e0e0e0;
            --accent-color: #4a90e2;
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Segoe UI', sans-serif;
        }

        body {
            background-color: #000;
            overflow-x: hidden;
            /* min-height: calc(100vh - 60px); 减去顶部导航高度*/

        }

        /* 顶部导航栏 */
        .top-nav {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            height: 60px;
            background: #1a1a1a;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.25);
            z-index: 1000;
            display: flex;
            align-items: center;
            padding: 0 20px;
            transition: transform 0.3s ease;
        {#border-bottom: 1px solid var(--border-color);#}
        }

        /* 汉堡菜单按钮 */
        .hamburger {
            color: #fff;
            font-size: 1.5rem;
            cursor: pointer;
            margin-right: 20px;
            display: none;
        }

        /* 顶部导航栏右侧功能 */
        .nav-tools {
            margin-left: auto;
            display: flex;
            gap: 15px;
            align-items: center;
        }

        /* 搜索框 */
        {#.search-box {#}
        {#    position: relative;#}
        {# } #}

        {#.search-input {#}
        {#    background: #2d2d2d;#}
        {#    border: none;#}
        {#    padding: 8px 35px 8px 15px;#}
        {#    border-radius: 20px;#}
        {#    color: #fff;#}
        {#    width: 200px;#}
        {#    transition: width 0.3s ease;#}
        {# } #}

        {#.search-input:focus {#}
        {#    outline: none;#}
        {#    width: 250px;#}
        {# } #}

        {#.search-btn {#}
        {#    position: absolute;#}
        {#    right: 10px;#}
        {#    top: 50%;#}
        {#    transform: translateY(-50%);#}
        {#    color: #fff;#}
        {#    cursor: pointer;#}
        {# } #}

        /* 登录按钮 */
        .login-btn {
            background: #007bff;
            color: #fff;
            border: none;
            padding: 8px 20px;
            border-radius: 20px;
            cursor: pointer;
            transition: background 0.3s ease;
            width: auto;
        }

        .login-btn:hover {
            background: #0056b3;
        }

        /* 左侧导航栏 */
        .side-nav {
            position: fixed;
            left: 0;
            top: 61px;
            bottom: 10px;
            width: 240px;
            background: #1a1a1a;
            box-shadow: 4px 0 12px rgba(0, 0, 0, 0.25);
            overflow-y: auto;
            z-index: 999;
            flex-shrink: 0; /*防止被压缩*/
        }

        /* collapsed状态：隐藏侧边栏 */
        .side-nav.collapsed {
            transform: translateX(-250px);
        }

        .side-nav.active {
            transform: translateX(0);
        }

        .side-nav.collapsed + .main-content {
            left: 10px; /*侧边栏收起时左间距归零*/
        }

        /* 主体内容 */
        .main-content {
        {#position: relative; /* 为绝对定位子元素提供参照 */#} position: absolute;
            top: 70px;
            left: 250px;
            right: 10px;
            bottom: 10px;
            flex-grow: 1; /*自动填充剩余空间*/
            transition: margin-left .3s ease; /*添加动画*/
            background: #1a1a1a;
            height: calc(100vh - 80px);
            padding: 20px;
            border-radius: 10px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.25);
            border: 1px solid #333;
            display: flex;
            justify-content: center; /* 子元素水平居中 */
            align-items: center; /* 子元素垂直居中 */
        }

        /* 导航菜单样式 */
        .nav-menu {
            list-style: none;
            padding: 15px;
        }

        .nav-item {
            margin: 8px 0;
        }

        .nav-link {
            color: #fff;
            text-decoration: none;
            padding: 12px;
            display: flex;
            align-items: center;
            border-radius: 6px;
            transition: all 0.3s ease;
        }

        .nav-link:hover {
            background: #2d2d2d;
        }

        .nav-link i {
            margin-right: 12px;
            width: 20px;
            font-size: 1.1rem;
        }

        /* 子菜单 */
        .sub-menu {
            list-style: none;
            padding-left: 30px;
            max-height: 0;
            overflow: hidden;
            transition: max-height 0.3s ease-out;
        }

        .sub-menu.active {
            max-height: 500px;
        }

        /* 移动端样式 */
        @media (max-width: 768px) {
            .hamburger {
                display: block;
            }

            .button☰ {
                display: none;
            }

            .side-nav {
                position: fixed;
                left: -250px; /* 完全隐藏导航栏 */
                width: 250px;
                height: 100vh;
                transition: transform 0.3s ease; /* 平滑动画 */
                z-index: 1000;
            }

            .side-nav.active {
                left: 0;
            }

            .nav-tools {
                display: none;
            }

            .mobile-tools {
                display: flex !important;
                gap: 15px;
            }

            .tab-float-container {
                left: 0; /* 改为全宽 */
                justify-content: flex-end; /* 内容右对齐 */
            }

        }

        /* 遮罩层 */
        .overlay {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0, 0, 0, 0.5);
            z-index: 998;
            display: none;
        }

        /* 登录引导样式 */
        .login-guide {
            max-height: 100vh;
            max-width: 100%;
            display: flex;
            align-items: center;
            justify-content: center;
        {#padding: 20px;#} text-align: center;
        {#align-content: center;#}{#align-self: flex-end;#}
        }

        .guide-content {
            height: 100%; /* 替换max-height为固定高度 */
            max-width: 100%;
            display: flex;
            flex-direction: column;
            align-items: center; /* 水平居中 */
            justify-content: center; /* 垂直居中 */
            color: var(--text-primary);
            font-size: 18px;
        }

        .guide-content h3 {
            margin: 15px 0;
            font-size: 18px;
            font-weight: 500;
        }

        .nav-links {
            list-style: none;
            padding: 20px;
        }

        .nav-links li {
            margin: 15px 0;
        }

        .nav-links a {
            color: var(--text-primary);
            text-decoration: none;
            display: block;
            padding: 12px;
            border-radius: 8px;
            transition: background 0.3s ease;
        }

        .nav-links a:hover {
            background: rgba(255, 255, 255, 0.05);
        }

        .nav-links .fas {
            width: 25px;
            margin-right: 10px;
        }

        /* 表单按钮伪装成链接 */
        .logout-form button {
            background: none;
            border: 0;
            color: #007bff;
            padding: 0;
            cursor: pointer;
        }

        .logout-form button:hover {
            text-decoration: underline;
        }

        /* 标签右浮动容器 (可选) */
        .tab-float-container {
            position: absolute; /* 绝对定位脱离文档流 */
            top: 0; /* 置顶 */
            left: 0; /* 靠左 */
            height: 60px;
            width: 100%;
            display: flex;
        {#align-items: center;#}{#flex-direction: row-reverse; /* 反向排列实现向右添加 */#}{#background: white;   /* 防止内容穿透 */#} z-index: 1000; /* 确保浮在最上层 */
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
            overflow-x: auto; /* 水平滚动条 */
            overflow-y: hidden;

        }

        /* 让滚动条更美观 */
        .tab-float-container::-webkit-scrollbar {
            height: 8px;
        }

        .tab-float-container::-webkit-scrollbar-thumb {
            background: #6F9183;
            border-radius: 4px;
        }

        /* 覆盖 Bootstrap 默认导航样式 */
        .tabs-cust {
            margin: 0 2px;
            height: 38px;
        }

        /* 移除tab标签下划线 */
        .nav-tabs {
            border-bottom: none !important; /* 移除底部边框（下划线） */
            display: inline-block; /* 让 ul 不换行 */
            white-space: nowrap; /* 强制 li 不换行 */
        }

        /* tab选中样式 */
        .nav-tabs .nav-link.active {
            background-color: #4CAF50 !important; /* 激活标签的背景色 */
        {#color: white !important; /* 激活标签的字体颜色 */#}
        }

        .nav-item {
            display: inline-block; /* li 横向排列 */
            float: none; /* 避免浮动影响 */
        }

        {% block style %} {% endblock %}

    </style>
    {% block script %} {% endblock %}

</head>

<body>
<!-- 遮罩层 -->
<div class="overlay" id="overlay"></div>
<!-- 顶部导航栏 -->
<nav class="top-nav">
    <i class="fas fa-bars hamburger" id="hamburger"></i>
    <button class="button☰" onclick="toggleSideNav()"
            style="background: none; border: none; color: white; font-size: 1.2rem;">☰
    </button>
    <div style="color: #109E87; margin-left: 10px;">管理系统 MGS</div>

    <!-- 桌面端功能按钮 -->
    <div class="nav-tools">
        {% if user.is_authenticated %}
            <div style="color: #109E87;">欢迎您:{{ user.username }} </div>
            <form action="{% url 'logout' %}" method="post" class="d-inline">
                {% csrf_token %}
                <button type="submit" class="btn btn-outline-info btn-sm">
                    <i class="bi bi-box-arrow-right me-1"></i>注销
                </button>
            </form>
        {% else %}
            <button class="login-btn py-1 px-3 fs-6"
                    onclick="window.location.href='{% url 'account:auth_login' %}'"
                    aria-label="跳转到登录页面">
                <i class="fas fa-user"></i> 登录
            </button>
        {% endif %}
    </div>

    <!-- 移动端功能按钮 -->
    <div class="nav-tools mobile-tools" style="display: none;">
        {% if user.is_authenticated %}
            <div style="color: #109E87;">{{ user.username }} </div>
            <form action="{% url 'logout' %}" method="post" class="d-inline">
                {% csrf_token %}
                <button type="submit" class="btn btn-outline-info btn-sm">
                    <i class="bi bi-box-arrow-right me-1"></i>注销
                </button>
            </form>
        {% else %}
            <button class="login-btn py-1 px-3 fs-6"
                    onclick="window.location.href='{% url 'account:auth_login' %}'"
                    aria-label="跳转到登录页面">
                <i class="fas fa-user"></i> 登录
            </button>
        {% endif %}
    </div>
</nav>

<!-- 左侧导航栏 -->
{% include 'account/partials/sidebar.html' %}

<!-- 右侧内容区 -->
<main class="main-content" id="mainContent">
    <!-- 首页内容 -->
    {% if is_begin %}
        {% if is_login %}
            {% include 'index_login.html' %}  <!-- 已登录首页 -->
        {% else %}
            {% include 'index.html' %}  <!-- 未登录首页 -->
        {% endif %}
    {% endif %}
    <!-- 菜单主体操作区 -->
    <div class="main-main">
        <!-- 标签导航 -->
        <div class="tab-float-container">
            <ul class="nav tabs-cust nav-tabs" id="contentTabs"></ul>
            <!-- 动态生成Tab标签 -->
        </div>
        <!-- 标签内容容器,需要增加顶部间距 -->
        <div class="tab-content" id="tabContent" style="margin-top: 60px;">
            <!-- 子页面将通过JS动态注入到这里 -->
        </div>

    </div>

    {% block main %}{% endblock %} {#占位代码块#}
</main>

<!-- Swal提示框JS链接 -->
<script src="https://unpkg.com/sweetalert2@11/dist/sweetalert2.min.js"></script>
<!-- 图片裁剪框js-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.5.12/cropper.min.js"></script>
{#<script src="https://cdn.jsdelivr.net/npm/cropperjs@latest/dist/cropper.min.js"></script>#}



<script>
    // 切换侧边栏
    function toggleSideNav() {
        document.querySelector('.side-nav').classList.toggle('collapsed');
    }

    // 汉堡菜单功能
    const hamburger = document.getElementById('hamburger');
    const sideNav = document.getElementById('sideNav');
    const overlay = document.getElementById('overlay');
    const mainContent = document.getElementById('mainContent');

    // 菜单切换功能
    document.querySelectorAll('.toggle-btn').forEach(btn => {
        btn.addEventListener('click', () => {
            btn.classList.toggle('active');
            btn.parentElement.querySelector('.sub-menu').classList.toggle('active');
        });
    });

    hamburger.addEventListener('click', () => {
        sideNav.classList.toggle('active');
        overlay.style.display = sideNav.classList.contains('active') ? 'block' : 'none';
    });

    // 点击遮罩层关闭菜单
    overlay.addEventListener('click', () => {
        sideNav.classList.remove('active');
        overlay.style.display = 'none';
    });

    // 响应式处理
    window.addEventListener('resize', () => {
        if (window.innerWidth > 768) {
            sideNav.classList.remove('active');
            overlay.style.display = 'none';
        }
    });

    // 点击外部关闭菜单（桌面端）
    document.addEventListener('click', (e) => {
        if (window.innerWidth > 768) return;
        if (!sideNav.contains(e.target) && !hamburger.contains(e.target)) {
            sideNav.classList.remove('active');
            overlay.style.display = 'none';
        }
    });

    // 菜单项自动收拢
    document.addEventListener('DOMContentLoaded', () => {
        const navMenu = document.querySelector('.nav-menu');
        if (!navMenu) {
            {#console.error('.nav-menu not found!');  因为还没有进入左侧导航栏#}
            return;
        }
        document.querySelector('.nav-menu').addEventListener('click', function (e) {
            const toggleBtn = e.target.closest('.toggle-btn');
            if (!toggleBtn) return;

            // 获取当前菜单ID
            const menuId = toggleBtn.dataset.menuId;
            {#const currentSubmenu = document.getElementById(menuId);#}
            // 关闭所有其他菜单
            document.querySelectorAll('.sub-menu.collapse').forEach(menu => {
                const collapseInstance = bootstrap.Collapse.getOrCreateInstance(menu); // 确保实例复用
                if (menu.id !== menuId) {
                    collapseInstance.hide();
                } else {
                    collapseInstance.show();
                }
            });
        });
    });

    // 标签页状态管理对象
    const tabManager = {
        tabs: new Set(),
        addTab: function (tabId, title, content) {
            // 创建导航标签
            const tabNav = document.createElement('li');
            tabNav.className = 'nav-item';
            tabNav.innerHTML = `
                <span class="nav-link tabs-cust" id="${tabId}-tab" data-bs-toggle="tab"
                   href="#${tabId}" role="tab" aria-controls="${tabId}"
                   style="color: #f0f0f0; background: #333">
                    ${title}
                    <button class="btn-close btn-close-white ms-2"
                            style="font-size: 0.5rem"
                            onclick="tabManager.closeTab('${tabId}')"></button>
                </span>
            `;

            // 创建内容面板
            const tabPane = document.createElement('div');
            tabPane.className = 'tab-pane fade';
            tabPane.id = tabId;
            tabPane.innerHTML = content;

            // 插入DOM
            document.getElementById('contentTabs').prepend(tabNav); //（右侧追加，默认行为）appendChild（左侧优先）prepend
            document.getElementById('tabContent').appendChild(tabPane);

            // 激活新标签
            new bootstrap.Tab(tabNav.querySelector('.nav-link')).show();
            this.tabs.add(tabId);
        },
        closeTab: function (tabId) {
            const tab = document.getElementById(`${tabId}-tab`).parentElement;
            const pane = document.getElementById(tabId);
            tab.remove();
            pane.remove();
            this.tabs.delete(tabId);
            contentCache.delete(tabId);
        }
    };

    // 点击子菜单时(AJAX加载内容)
    const contentCache = new Map();

    function loadContent(url, title) {
        // 首页与菜单主体区域,隐藏add('d-none'),显示remove('d-none')/*Bootstrap类隐藏*/
        document.querySelector('.index').classList.add('d-none');
        document.querySelector('.main-main').classList.remove('d-none');

        if (contentCache.has(url)) {
            const cachedData = contentCache.get(url);
            // 如果对应的Tab仍然存在（未被关闭）
            if (cachedData.tabId && document.getElementById(cachedData.tabId)) {
                // 激活对应的导航项和Tab页
                activateExistingTab(cachedData.tabId);
                return false; //阻止后续新建逻辑
            }
            // 如果缓存存在但DOM已被移除，清除无效缓存
            contentCache.delete(url);
        }

        fetch(`${url}?is_ajax=1`)
            .then(response => response.json())  // 解析 JSON
            .then(data => {
                // data.html → HTML 片段（直接插入）; data.data → JSON 数据（可单独使用）
                const tabId = data.data.tabId
                contentCache.set(url, {url: data.html, tabId: tabId})
                contentCache.set(tabId, tabId)
                tabManager.addTab(tabId, title, data.html); // 激活tab标签页:static/js/里的:标签页状态管理对象
                data.js_files.forEach(file => {
                    const script = document.createElement('script');
                    script.src = `${file.path}?v=${Date.now()}`;
                    script.dataset.moduleId = crypto.randomUUID(); // 或使用其他生成方式
                    {% if file.type == 'esm' %}
                        script.type = 'module';
                    {% else %}
                        script.textContent = `(function(uid){ ${file.inlineCode || ''} })("${script.dataset.moduleId}")`;
                    {% endif %}
                    document.body.appendChild(script);
                });
            })
            .catch(error => console.error("AJAX error:", error));
    }

    // 点击主菜单时(暂决定显不显示首页)
    function loadMenu(name) {
        if (name === '首页') {
            document.querySelector('.index').classList.remove('d-none');  // 显示
            document.querySelector('.main-main').classList.add('d-none');  // 隐藏
        }
    }

    // 专用函数：激活已存在的Tab页
    function activateExistingTab(tabId) {
        const tabTrigger = document.querySelector(`[href="#${tabId}"], [data-bs-target="#${tabId}"]`);
        // 方式1：Bootstrap5+原生API
        if (typeof bootstrap !== 'undefined') {
            if (tabTrigger) new bootstrap.Tab(tabTrigger).show();
        }
        // 方式2：模拟点击（兼容旧版）
        else {
            if (tabTrigger) tabTrigger.click();
        }
        // 更新URL哈希
        window.history.replaceState(null, null, `#${tabId}`);
    }

    // 监听标签切换事件
    document.getElementById('tabContent').addEventListener('shown.bs.tab', function (e) {
        const activeTab = e.target.getAttribute('aria-controls');
        window.history.replaceState(null, null, `#${activeTab}`);
    });

    // 辅助函数：显示Toast通知
    {#let toastTimer = null; // 全局保存定时器ID#}
    function showToast(message, type='success', position='top-end') {
        // 清除历史定时器
        {#if (toastTimer) clearTimeout(toastTimer);#}
        const colorMap = {
            error: '#FC9DAF',
            success: '#48bb78',
            warning: '#FEDEE4',
            info: '#EFF6FF',
        };
        // 实现Toast通知逻辑
        const Toast = Swal.mixin({
            toast: true,
            position: position,
            showConfirmButton: false,
            timer: 3000,
            timerProgressBar: true,  // 进度条
            background: colorMap[type] || '#F9F9F9',
            {#didOpen: (toast) => {#}
            {#  toast.querySelector('.swal2-timer-progress-bar').style.background = '#f6ad55';  // 进度条颜色#}
            {# },#}
            {#background: '#FFE6F0',  // 修改背景色#}
            {#color: '#ffffff',       // 修改文字颜色#}
            {#iconColor: '#68d391',   // 修改图标颜色#}
            {#didOpen: (toast) => {#}
            {#    // 添加全局点击监听器#}
            {#    document.addEventListener('click', handleGlobalClick(toast));#}
            {# },#}
            {#willClose: () => {#}
            {#    // 移除监听器防止内存泄漏#}
            {#    document.removeEventListener('click', handleGlobalClick);#}
            {# }#}
         });
        // 创建点击处理器
        {#const handleGlobalClick = (toast) => (e) => {#}
        {#    // 排除Toast自身区域的点击#}
        {#    if (!toast.contains(e.target)) {#}
        {#        Toast.close();#}
        {#    }#}
        {# }#}
        Toast.fire({
            icon: type,
            title: message,
            {#background: type === 'error' ? '#f56565' : '#48bb78', // 红/绿背景#}
            {#iconColor: type === 'warning' ? '#ed8936' : 'white'   // 黄标/白标#}
        });
        // 设置新定时器
        {#toastTimer = setTimeout(() => {#}
            {#Toast.hide()#}
        {#    toastTimer = null; // 重置引用#}
        {# }, 3000);#}
    }

    // 删除提示框使用示例:
    {#Swal.fire({#}
    {#  title: '确认删除',#}
    {#  text: `确定要删除横幅 "${bannerTitle}" 吗？此操作不可恢复。`,#}
    {#  icon: 'warning',#}
    {#  showCancelButton: true,#}
    {#  confirmButtonColor: '#d33',#}
    {#  cancelButtonColor: '#3085d6',#}
    {#  confirmButtonText: '确认删除',#}
    {#  cancelButtonText: '取消'#}
    {#  }).then((result) => {#}
    {#  if (result.isConfirmed) {#}
    {#    deleteBanner(bannerId, bannerTitle);#}
    {#  }#}
    {# });#}

    // 删除提示框位置说明:
    //'top':显示在页面顶部居中位置
    //'top-start':位于页面顶部左侧
    //'top-end':位于页面顶部右侧
    //'center':居中显示在页面正中央
    //'center-start':位于页面中部左侧
    //'center-end':位于页面中部右侧
    //'bottom':位于页面底部居中
    //'bottom-start':位于页面底部左侧
    //'bottom-end':位于页面底部右侧

    {% block js %}{% endblock %} {#占位代码块#}

</script>

<!-- 去除模态框警告用 -->
<script src="{% static '/js/inert-polyfill.min.js' %}"></script>

<!-- 先引入jQuery -->
<script src="{% static '/js/jquery-3.7.1.min.js' %}"></script>
<!-- 再引入Bootstrap JS（完整版或单独modal.js） -->
<script src="{% static '/bootstrap5.23/bootstrap.bundle.min.js' %}" defer></script>

<script src="{% static 'ecom/product/js/categoryTree.js' %}"></script> <!-- 分类下拉框使用 -->



<script src="{% static '/js/loadPage.js' %}"></script> <!-- 分页模块 -->

</body>

</html>
